import React, { useState, useCallback } from 'react';
import { Avatar, Button, message, Modal, Slider, Icon } from 'antd';
import img from '@/assets/logo2.png';
import Cropper from 'react-easy-crop';
import { eventTrack } from '@/utils/track';
import { uploadFn } from './uploadImage';
import enlarge from './images/enlarge.png';
import narrow from './images/narrow.png';
import defaultImg from './images/default.jpg';
import styles from './index.less';

// 裁切
import UploadOss from './UploadOss';
import getCroppedImg from './cropImage';

import 'canvas-toBlob';

const uploadUrl = '/api/resource/public/oss/producePutPreSignUrls';

const UploadAvatar = React.forwardRef(({ value = { allFileList: [] }, editable, onChange }, ref) => {
    const { allFileList = [] } = value;
    const [visibleAvatar, setVisibleAvatar] = useState(false);
    const [visibleUpLoad, setVisibleUpLoad] = useState(false);
    const [fileList, setFileList] = useState([]);
    const [uploadParams, setUploadParams] = useState([]);

    const [uploadLoading, setUploadLoading] = useState(false);

    // 图片裁切
    const [crop, setCrop] = useState({ x: 0, y: 0 });
    const [zoom, setZoom] = useState(1);
    const [croppedAreaPixels, setCroppedAreaPixels] = useState(null);
    const onCropComplete = useCallback((croppedArea, areaPixels) => {
        setCroppedAreaPixels(areaPixels);
    }, []);

    const [imageSrc, setImageSrc] = useState(null);
    const [newImage, setNewImage] = useState(null);

    const handleAvatar = () => {
        setVisibleUpLoad(true);
        if (allFileList.length > 0) {
            setUploadParams({
                categoryCode: 'avatarFile',
                keyNameAndOpt: [`ADD:${allFileList[allFileList.length - 1].keyName}`]
            });
            setImageSrc(allFileList[allFileList.length - 1].url || allFileList[allFileList.length - 1].thumbUrl);
        } else {
            setUploadParams({
                categoryCode: 'avatarFile',
                keyNameAndOpt: []
            });
            setFileList([]);
            setImageSrc(defaultImg);
        }
        // 初始化
        setCrop({ x: 0, y: 0 });
        setZoom(1);
    };

    // 上传
    const changeAllFileList = (showFileList, uploadResource) => {
        if (uploadResource.keyNameAndOpt.length > 0) {
            setUploadParams(uploadResource);
            setImageSrc(showFileList ? showFileList[0].thumbUrl : defaultImg);
        } else if (allFileList.length > 0) {
            setUploadParams({
                categoryCode: 'avatarFile',
                keyNameAndOpt: [`ADD:${allFileList[allFileList.length - 1].keyName}`]
            });
            setImageSrc(allFileList[allFileList.length - 1].url);
        }
        setFileList(showFileList);
    };

    // 取消头像弹窗
    const handleCancelAvatar = () => {
        setVisibleAvatar(false);
        setVisibleUpLoad(false);
    };

    // base64 转成file
    const dataURLtoFile = (dataurl, filename) => {
        const arr = dataurl.split(',');
        const mime = arr[0].match(/:(.*?);/)[1];
        const bstr = atob(arr[1]);
        let n = bstr.length;

        const u8arr = new Uint8Array(n);
        // eslint-disable-next-line no-plusplus
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }

        return new File([u8arr], filename, { type: mime });
    };

    // 成功回调
    const onSuccess = (preUrl, file, uploadResourceFile) => {
        onChange({
            preUrl,
            file,
            allFileList: fileList,
            uploadResourceFile
        });
        setVisibleUpLoad(false);
        setUploadLoading(false);
    };
    // 失败
    const onError = () => {
        setUploadLoading(false);
    };

    // 裁切，提交
    const showCroppedImage = useCallback(async () => {
        try {
            let imgName = '';
            const { keyNameAndOpt = [] } = uploadParams || {};
            if (keyNameAndOpt.length > 0) {
                const tempArr = keyNameAndOpt[keyNameAndOpt?.length - 1].split('_');
                imgName = String(tempArr?.length > 1 ? tempArr[1] : '').toLocaleLowerCase();
            }
            const croppedImage = await getCroppedImg(imageSrc, croppedAreaPixels);

            setNewImage(croppedImage);
            // 调用
            const files = dataURLtoFile(croppedImage, imgName);
            // 截图的图片处理，上传
            uploadFn(uploadUrl, files, uploadParams, onSuccess, onError);
        } catch {
            setUploadLoading(false);
            message.error('上传失败');
        }
    }, [croppedAreaPixels, imageSrc, onSuccess, uploadParams]);

    // 保存头像
    const handleUpdate = () => {
        setUploadLoading(true);
        showCroppedImage();
    };
    // 图片滑动缩放
    const handleReverseChange = value2 => {
        setZoom(value2);
    };
    // 图片点击滑动缩放
    const handleSlider = type => {
        if (type === 0) {
            setZoom(zoom - 0.1);
        } else {
            setZoom(zoom + 0.1);
        }
    };

    return (
        <div className={styles.userCard} ref={ref}>
            <div className={styles.uploadFather}>
                {editable &&
                    (allFileList && allFileList.length > 0 ? (
                        <div className={`${styles.upload} ${editable ? styles.current : null}`} onClick={handleAvatar}>
                            <Avatar
                                icon="user"
                                src={allFileList && allFileList.length > 0 ? newImage || allFileList[0].url : ''}
                                size={72}
                                style={{ flex: '0 0 80px' }}
                            />
                            <div className={styles.text}>重新上传</div>
                        </div>
                    ) : (
                        <div className={styles.upload} onClick={handleAvatar}>
                            <Avatar size={72} style={{ flex: '0 0 80px' }}>
                                <div
                                    style={{
                                        position: 'relative',
                                        width: 72,
                                        height: 72
                                    }}
                                >
                                    <div
                                        style={{
                                            position: 'absolute',
                                            left: '50%',
                                            top: '50%',
                                            transform: 'translate(-50%, -50%)',
                                            lineHeight: 1
                                        }}
                                    >
                                        <Icon type="plus" style={{ fontSize: '22px' }} />
                                        <div style={{ lineHeight: 1, fontSize: 12, marginTop: 6 }}>上传图片</div>
                                    </div>
                                </div>
                            </Avatar>
                        </div>
                    ))}
                {!editable && (
                    <Avatar
                        style={{ border: 'solid 1px #f2f2f2' }}
                        icon="user"
                        src={allFileList && allFileList.length > 0 ? newImage || allFileList[0].url : ''}
                        size={72}
                    />
                )}
                {allFileList && allFileList.length > 0 && (
                    <div className={styles.avatarBtn}>
                        <a
                            style={{ color: 'rgba(0,0,0,.45)' }}
                            onClick={() => {
                                setVisibleAvatar(true);
                                eventTrack({
                                    eventName: 'personal_my_info_picture_view_click',
                                    pageName: 'personal_my_info'
                                });
                            }}
                        >
                            查看
                        </a>
                        <a
                            style={{ color: 'rgba(0,0,0,.45)' }}
                            href={
                                allFileList && allFileList.length > 0
                                    ? allFileList[allFileList.length - 1].url ||
                                      allFileList[allFileList.length - 1].thumbUrl
                                    : ''
                            }
                            onClick={() => {
                                eventTrack({
                                    eventName: 'personal_my_info_picture_download_click',
                                    pageName: 'personal_my_info'
                                });
                            }}
                        >
                            下载
                        </a>
                    </div>
                )}
            </div>
            <Modal
                title="查看图片"
                visible={visibleAvatar}
                destroyOnClose
                footer={false}
                maskClosable={false}
                onCancel={() => {
                    handleCancelAvatar();
                }}
                centered
            >
                <div className={styles.selectAvatar}>
                    <img
                        src={
                            allFileList && allFileList.length > 0
                                ? newImage || allFileList[allFileList.length - 1].url
                                : ''
                        }
                        alt=""
                    />
                </div>
            </Modal>
            <Modal
                title="修改头像"
                visible={visibleUpLoad}
                width={692}
                maskClosable={false}
                destroyOnClose
                // footer={false}
                confirmLoading={uploadLoading}
                onCancel={() => {
                    handleCancelAvatar();
                }}
                centered
                onOk={handleUpdate}
            >
                <div className={styles.avatarCtr}>
                    <div className={styles.infoLeft}>
                        <div className={styles.cropAvatar}>
                            <div className={styles.cropContainer}>
                                <Cropper
                                    image={imageSrc}
                                    crop={crop}
                                    zoom={zoom}
                                    showGrid={false}
                                    cropShape="round"
                                    aspect={1}
                                    onCropChange={setCrop}
                                    onCropComplete={onCropComplete}
                                    onZoomChange={setZoom}
                                />
                            </div>
                        </div>
                        <div className={styles.controls}>
                            {zoom > 1 ? (
                                <span
                                    className={styles.narrow}
                                    onClick={() => {
                                        handleSlider(0);
                                    }}
                                >
                                    <img src={narrow} alt="" />
                                </span>
                            ) : (
                                <span className={styles.narrow}>
                                    <img src={narrow} alt="" />
                                </span>
                            )}
                            <div className={styles.slider}>
                                <Slider
                                    value={zoom}
                                    min={1}
                                    max={3}
                                    step={0.1}
                                    aria-labelledby="Zoom"
                                    onChange={handleReverseChange}
                                    classes={{ container: 'slider' }}
                                />
                            </div>
                            {zoom <= 3 ? (
                                <span
                                    className={styles.enlarge}
                                    onClick={() => {
                                        handleSlider(1);
                                    }}
                                >
                                    <img src={enlarge} alt="" />
                                </span>
                            ) : (
                                <span className={styles.narrow}>
                                    <img src={narrow} alt="" />
                                </span>
                            )}
                        </div>
                    </div>
                    <div className={styles.infoRight}>
                        <p className={styles.avatarTitle}>头像规范：</p>
                        <div className={styles.infoText}>
                            <p>● 本人近期（半年内）正面彩色半身证件照 </p>
                            <p>● 照片背景为白色，二寸近照</p>
                            <p>● 照片上人像清晰，层次丰富，神态自然</p>
                            <p>● 照片可识别度高，不得带有戴帽子/有色眼镜/口罩等遮盖物</p>
                        </div>
                        <UploadOss
                            dragAble={false}
                            fileList={fileList}
                            uploadUrl={uploadUrl}
                            checkFileSize={3}
                            checkFileSizeMsg="文件大小不可超过3M，请重新选择"
                            sysCode="OA"
                            setFileList={changeAllFileList}
                            businessCode="SysAvatar"
                            categoryCode="avatarFile"
                            isSingle
                            checkFileLength={1}
                            checkFileLengthMsg="只能上传一张图片"
                            checkFileType="JPG,JPEG,PNG"
                            checkFileTypeMsg="只能上传JPG,JPEG,PNG格式的文件！"
                            isToBase64
                            disabled={!editable}
                        >
                            <Button>
                                <Icon type="upload" /> 上传照片
                            </Button>
                        </UploadOss>
                    </div>
                </div>
            </Modal>
        </div>
    );
});

export default UploadAvatar;
